package com.lap.gateway.filter;

import com.lap.framework.constant.Header;
import com.lap.framework.tools.Uid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 链路ID
 *
 * @author Shuisheng Lao(劳水生)
 * @version 0.0.1
 */
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
@Component
public class RequestIdFilter implements GlobalFilter {

  @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    String requestId = exchange.getRequest().getHeaders().getFirst(Header.REQUEST_ID);
    if (StringUtils.isBlank(requestId)) {
      requestId = Uid.getOrgId();
    }

    MDC.put(Header.REQUEST_ID, requestId);
    ServerHttpRequest request =
        exchange.getRequest().mutate().header(Header.REQUEST_ID, requestId).build();

    return chain
        .filter(exchange.mutate().request(request).build())
        .doFinally(signalType -> MDC.remove(Header.REQUEST_ID));
  }
}
